define(
	[
		'require',
		'./center_ctrl',
		'./detail_ctrl'
	],
	function(require) {
		function toThousands(num) {
			var result = '',
				counter = 0;
			num = (num || 0).toString();
			for (var i = num.length - 1; i >= 0; i--) {
				counter++;
				result = num.charAt(i) + result;
				if (!(counter % 3) && i != 0) {
					result = ',' + result;
				}
			}
			return result;
		}
		APM.BusinessOverviewController = Ember.Controller.extend({

			needs: ["businessCenter", "businessDetail", "BusinessDetailGauge"],

			business: Ember.computed.alias('controllers.businessDetail.model'),

			isNodeUnSelected: Ember.computed("selectedNodes", function(key, value) {
				var len = this.get("selectedNodes.length");
				return len == null || len == 0;
			}),

			enterDelete: true,

			isTradingMode: true,

			businessLineData: Ember.A([]),

			today: Ember.computed(function() {
				return APM.util.formatDate(new Date(new Date() - timeD_value), "D");
			}),

			//添加应用系统
			addApplication: function(params) {
				return this.store.ajax("PUT", "applications/fromOverview", params);
			},
			//保存应用系统
			saveApplication: function(arr) {
				return this.store.ajax("PUT", "applications/save/inOverview", arr);
			},
			//删除应用系统
			deleteApplication: function(app, params) {
				return this.store.ajax("PUT", "applications/" + app.id + "/fromOverview", params);
			},
			//获取当前所有应用系统
			allApplication: function(params) {
				return this.store.ajax("GET", "applications/inOverview", params);
			},
			init: function() {
				var that = this;
				this.overviewPageSystem();
				this.set('enterDelete', true);
				this.set('isDelete', false);
				if (!$.cookie("isThreshold")) {
					overviewOrCenterSwitch = "business";
				}
				if (this.get("auth.user").role != 1) {
					this.set("administrators", true);
				}
			},
			nodeKeywordChange: Ember.observer("nodeKeyword", function() {
				this.requireNodes({
					keyWord: this.get("nodeKeyword")
				});
			}),
			/*
				向服务端请求节点列表
			*/
			requireNodes: function(params) {
				var ctrl = this,
					appId = this.get("business.id"),
					serchValue = this.get("nodeKeyword");
				ctrl.set("nodes", Ember.A([{
					_displayName: "暂时没有这个应用系统..."
				}]));
				return ctrl.store.ajax("GET", "applications/inOverview", params)
					.then(function(response) {
						var nodes = Ember.A(response.applications);
						nodes.forEach(function(node) {
							var html = '';
							html += node.name ? node.name : (node.ip + ':' + node.port);
							var ip = node.ip;
							var title = 'IP:' + node.ip + ' 端口：' + node.port;
							node._title = new Ember.Handlebars.SafeString(title);
							node._displayName = new Ember.Handlebars.SafeString(html);
							node._displayFlow = APM.util.flowFormatter(node.flow);
							node.protocolName = new Ember.Handlebars.SafeString(ip);
						});
						ctrl.set("nodes", nodes);
					});
			},

			activeNextGroup: function() {
				var size = 5,
					index = this.get("curGroupIndex"),
					apps = this.get("applications"),
					appsLen = apps.length,
					groupNum = Math.ceil(appsLen / size),
					activeAppGroup;

				if (index + 1 == groupNum) {
					this.requireApplications();
				} else {
					this.set("curGroupIndex", ++index);
					activeAppGroup = Ember.A(apps.slice(index * size, Math.min(appsLen, (index + 1) * size)));
					this.requirePerformances(activeAppGroup);
				}
			},
			reset: function() {
				this.set("model", null);
				this.set("nodes", null);
				this.set("curGroupIndex", null);
			},
			calculationTime: function() {
				var startDate, endDate;

				endDate = new Date(new Date() - timeD_value);
				endDate.setMinutes(endDate.getMinutes() - 1);
				endDate.setSeconds(0);
				endDate.setMilliseconds(0);
				startDate = new Date(+endDate);
				var minutes = startDate.getMinutes() - 30;
				if (minutes <= 0) {
					minutes = 60 - Math.abs(minutes);
					startDate.setHours(startDate.getHours() - 1);
				}
				startDate.setMinutes(minutes);

				if (isLocalDebugModel) {
					endDate = new Date(2014, 9, 1, 12, 0, 0);
					startDate = new Date(+endDate)
					startDate.setHours(startDate.getHours() - 1);
				}
				return {
					"endDate": endDate,
					"startDate": startDate
				};
			},
			overviewPageSystem: function() {
				var ctrl = this,
					startDate = ctrl.calculationTime().startDate,
					endDate = ctrl.calculationTime().endDate;
				ctrl.allApplication({
						"isOverview": "true",
						"startDate": +startDate,
						"endDate": +endDate
					})
					.then(function(response) {
						var applications = Ember.A(response.applications);
						ctrl.set("menu", applications);
						ctrl._requirePerformances();
					});
			},
			clickSetButton: function() {
				var ctrl = this;
				$(".application-main-box").css("padding", 0);
				$(document).on("click", function() {
					$(".business-set .business-overview-addOrDelete").hide();
				});
				setTimeout(function() {
					$(".business-set").on("click", function(event) {
						$(".business-set .business-overview-addOrDelete").show();
						event.stopPropagation();
					});
					$(".deleteBtn").on("click", function(event) {

						var model = ctrl.get("model"),
							saveApplicationArr = [];
						model.forEach(function(app) {
							saveApplicationArr.push(app.id);
						});
						ctrl.set("saveApplicationArr", saveApplicationArr);;
						ctrl.set('isDelete', true);
						ctrl.set('isCancel', true);
						ctrl.set('enterDelete', false);
						$(".business-set .business-overview-addOrDelete").hide();
						$(".business-set").hide();
						$(".business-overview-setwrap .cancel").show();
						$(".business-overview-setwrap .save").show();
						event.stopPropagation();
					});
					$(".addBtn").on("click", function(event) {

						ctrl.requireNodes({
							"isOverview": "false"
						});

						Broada.getView("BusinessOverview").openDialog();

						ctrl.set("nodeKeyword", '');

						$(".ui-dialog").css('z-index', 2147483648);

						$(".business-set .business-overview-addOrDelete").hide();

						event.stopPropagation();
					});
					$(".business-overview-setwrap .cancel").on("click", function(event) {
						ctrl.overviewPageSystem();
						$(".business-overview-setwrap .cancel").hide();
						$(".business-overview-setwrap .save").hide();
						$(".business-set").show();
						ctrl.set('isDelete', false);
					});
					$(".business-overview-setwrap .save").on("click", function(event) {
						var saveApplicationArr = ctrl.get("saveApplicationArr");
						$(".business-overview-setwrap .cancel").hide();
						$(".business-overview-setwrap .save").hide();
						$(".business-set").show();
						ctrl.set('isDelete', false);
						ctrl.saveApplication(saveApplicationArr);
					});
				}, 0);

			},
			actions: {
				moveUpApplication: function(app) {
					var model = this.get('model'),
						prev = model[model.indexOf(app) - 1];
					this.send('swapBusinessApplication', prev.id, app.id);
				},

				moveDownApplication: function(app) {
					var model = this.get('model'),
						next = model[model.indexOf(app) + 1];
					this.send('swapBusinessApplication', app.id, next.id);
				},
				deleteApplication: function(app) {
					var ctrl = this;
					var arr = [];
					arr.push(app.id);
					confirmDialog('确定要删除业务系统么？')
						.then(function() {
							ctrl.addApplication({
									"isOverview": false,
									"appIds": arr
								})
								.then(function() {
									ctrl.overviewPageSystem();
								});
						});
				},

				swapBusinessApplication: function(id1, id2) {
					var ctrl = this;
					this.store.ajax("POST", "applications/business/changeorder", {
						id1: id1,
						id2: id2
					}).then(function() {
						ctrl.overviewPageSystem();
					})
				},
				save: function() {

				},
				deleteBusinessLine: function(item) {
					var model = this.get("model"),
						modelId = item.id,
						ctrl = this,
						saveApplicationArr = [];

					confirmDialog("是否删除选中的交易？")
						.then(function() {
							var newModel = model.filter(function(app) {
								if (app.id != item.id) {
									saveApplicationArr.push(app.id);
								}
								return app.id != modelId;
							});
							ctrl.set("saveApplicationArr", saveApplicationArr);
							ctrl.set("model", Ember.A(newModel));
							ctrl.set("menu", Ember.A(newModel));
						});
				},
				dialogCancel: function() {
					Broada.getView("BusinessOverview").closeDialog();
				},

				queryNode: function() {
					var ctrl = this;
					ctrl.requireNodes({
						"isOverview": "false",
						"keyWord": this.get('nodeKeyword') || ''
					});
				},

				selectRelationNode: function(node, index) {
					if (!node.id) {
						return;
					}

					var status = this.get("nodes")[index].isSelected;


					this.set("selectedNodes", Ember.A([node]));
					// this.get("nodes").forEach(function(node){
					// 	Ember.set(node, "isSelected", false);
					// });
					if (!node["isSelected"]) {
						Ember.set(node, "isSelected", true);
					} else {
						Ember.set(node, "isSelected", false);
					}


				},
				addBusinessLine: function() {
					var nodes = this.get('nodes'),
						ctrl = this,
						total = "business/number/total",
						apps = [];
					nodes.forEach(function(node, index) {
						if (node.isSelected) {
							apps.push(node.id);
						}
					});
					ctrl.addApplication({
							"appIds": apps,
							"isOverview": true
						})
						.then(function(response) {
							if (response.status != "success") {
								return;
							}
							ctrl.overviewPageSystem();
							ctrl.set("isHaveData", true);
							Broada.getView("BusinessOverview").closeDialog();
						});
				},
				sequenceItemClick: function(args, view) {
					var ctrl = this;
					switch (view.displayMode) {
						case "detail":
							this.set("timePoint", args.timestamp);
							setTimeout(function() {
								$.cookie("isThreshold", "", -1);
								overviewOrCenterSwitch = "business";
								ctrl.transitionToRoute("business.detail.gauge", view.appData.id, {
									queryParams: {
										startTime: args.timestamp,
										pinTimePoint: true
									}
								});

							}, 10);
							break;
					}
				}
			},

			//数据
			_requirePerformances: function() {
				var ctrl = this,
					startDate = ctrl.calculationTime().startDate,
					endDate = ctrl.calculationTime().endDate;

				var applications = ctrl.get("menu");
				return this.get("controllers.businessCenter").requirePerformances(applications, true, startDate, endDate)
					.then(function(response) {
						Ember.A(applications).forEach(function(app, index) {
							if (response[app.id + "lastPerf"]) {
								Ember.set(app, "volume", toThousands(response[app.id + "lastPerf"]["business_throughput_total"]));
							} else {
								Ember.set(app, "volume", "-");
							}
						});
						ctrl.set("model", applications);

						ctrl._setAppXAxisTime();
						return applications;
					});
			},

			_setAppXAxisTime: function(apps) {
				var applications = Ember.A(apps || this.get("model"));
				var set = Ember.set,
					ctrl = this,
					formatDate = APM.util.formatDate;
				applications.forEach(function(app) {
					var performances = app.performances;
					ctrl.set('axisLength', performances.length);
					set(app, "startXAxisTime", formatDate(performances[0].timestamp, "t"));
					set(app, "endXAxisTime", formatDate(performances[performances.length - 1].timestamp, "t"));
				});
			},
			stopRealTimeMode: function() {
				clearTimeout(this.timeTicket);
				this.timeTicket = null;
			},
			startRealTimeMode: function() {
				if (this.timeTicket) {
					return;
				}
				_requireData(this);

				function _requireData(ctrl) {
					var bOk = false;
					var interval = 5000;
					if (isLocalDebugModel) {
						interval = 6000;
					}
					ctrl.timeTicket = setTimeout(function() {

						ctrl._requirePerformances()
							.then(function(response) {
								_requireData(ctrl);
							}, function() {
								_requireData(ctrl);
							});

					}, interval);
				}
			}
		})
	});